package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.dto.ClubLeaderDto;
import com.zz.entity.Club;
import com.zz.entity.ClubLeader;
import com.zz.entity.SystemNotice;
import com.zz.entity.User;
import com.zz.mapper.ClubLeaderMapper;
import com.zz.mapper.ClubMapper;
import com.zz.mapper.SystemNoticeMapper;
import com.zz.mapper.UserMapper;
import com.zz.service.ClubLeaderService;
import com.zz.service.SystemNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HUAWEI
 */
@Service
@Slf4j
@Validated
public class ClubLeaderServiceImpl extends ServiceImpl<ClubLeaderMapper, ClubLeader> implements ClubLeaderService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClubLeaderMapper clubLeaderMapper;

    @Autowired
    private ClubMapper clubMapper;

    @Autowired
    private SystemNoticeMapper systemNoticeMapper;

    @Override
    public R<String> apply(int clubId, HttpServletRequest request) {
        String userName = (String) request.getSession().getAttribute("user");
        // 条件查询器
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<User>();
        userWrapper.eq(User::getName, userName);
        User user = userMapper.selectOne(userWrapper);

        // 获取用户学号
        int userId = user.getId();

        // 条件查询器
        LambdaQueryWrapper<ClubLeader> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClubLeader::getClubId, clubId).eq(ClubLeader::getUserId, userId);
        ClubLeader clubLeader = clubLeaderMapper.selectOne(wrapper);

        if (clubLeader != null){
            // 已申请未被审核
            if (clubLeader.getStatus() == 0){
                return R.error("你已经申请过了！不能重复提交申请！");
            }
            if (clubLeader.getStatus() == 1 && clubLeader.getOperate() == 1){
                return R.error("你已经成为社团负责人了！不能再次申请！");
            }
        }

        ClubLeader leader = new ClubLeader();
        leader.setUserId(userId);
        leader.setClubId(clubId);
        clubLeaderMapper.insert(leader);

        return R.success("你已经成功提交申请！等待社团负责人审核！");
    }

    @Override
    public R<Page> applyList(int page, int pageSize, HttpServletRequest request) {
        // 获取当前社团编码
        int clubId = (int) request.getSession().getAttribute("club");

        Page<ClubLeader> pageInfo = new Page<>(page, pageSize);
        Page<ClubLeaderDto> clubLeaderDtoPage = new Page<>(page, pageSize);

        // 条件查询器
        LambdaQueryWrapper<ClubLeader> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClubLeader::getClubId, clubId).eq(ClubLeader::getStatus, 0);

        // 执行分页查询
        // 在page方法内部会将查好的数据封装，赋好值给pageInfo
        clubLeaderMapper.selectPage(pageInfo,wrapper);

        // 对象拷贝(除了records,records其实就是页面中一整行一整行数据)
        BeanUtils.copyProperties(pageInfo,clubLeaderDtoPage,"records");

        List<ClubLeader> records = pageInfo.getRecords();
        // 遍历list集合对象,item即为获取到的一个个Activity对象
        List<ClubLeaderDto> list = records.stream().map((item) -> {
            ClubLeaderDto clubLeaderDto = new ClubLeaderDto();
            // 将其clubLeader中的数据复制给clubLeaderDto
            BeanUtils.copyProperties(item,clubLeaderDto);

            // 根据id查询分类对象
            Club club = clubMapper.selectById(clubId);
            User user = userMapper.selectById(item.getUserId());

            if (club != null){
                clubLeaderDto.setClubName(club.getName());
            }

            if (user != null){
                clubLeaderDto.setUserName(user.getName());
            }
            return clubLeaderDto;
        }).collect(Collectors.toList());// 把以上创建的dto对象都收集起来

        clubLeaderDtoPage.setRecords(list);

        return R.success(clubLeaderDtoPage);
    }

    @Override
    public R<String> agree(int id) {
        // 条件查询器
        ClubLeader leader = clubLeaderMapper.selectById(id);
        leader.setStatus(1);
        leader.setOperate(1);

        // 同步更新数据库
        clubLeaderMapper.updateById(leader);

        // 发送系统通知信息
        User user = userMapper.selectById(leader.getUserId());
        Club club = clubMapper.selectById(leader.getClubId());
        SystemNotice systemNotice = new SystemNotice();
        systemNotice.setUserId(leader.getUserId());
        systemNotice.setTitle("您收到一条来自社团"+club.getName()+"的通知！");
        systemNotice.setInfo(user.getName()+"同学你好！恭喜你成为社团"+club.getName()+"的负责人！让我们一起努力让社团变得更好！");
        systemNotice.setTime(new Date(System.currentTimeMillis()));

        systemNoticeMapper.insert(systemNotice);

        return R.success("同意该用户成为社团负责人！");
    }

    @Override
    public R<String> decline(int id) {
        // 条件查询器
        ClubLeader leader = clubLeaderMapper.selectById(id);

        // 发送系统通知信息
        User user = userMapper.selectById(leader.getUserId());
        Club club = clubMapper.selectById(leader.getClubId());
        SystemNotice systemNotice = new SystemNotice();
        systemNotice.setUserId(leader.getUserId());
        systemNotice.setTitle("您收到一条来自社团"+club.getName()+"的通知！");
        systemNotice.setInfo(user.getName()+"同学你好！很遗憾你没有成为社团"+club.getName()+"的负责人！");
        systemNotice.setTime(new Date(System.currentTimeMillis()));

        systemNoticeMapper.insert(systemNotice);

        // 同步更新数据库
        clubLeaderMapper.deleteById(leader);

        return R.success("不同意该用户成为社团负责人！");
    }

    @Override
    public R<String> add(int userId, int clubId) {
        // 新增leader
        ClubLeader leader = new ClubLeader();
        leader.setUserId(userId);
        leader.setClubId(clubId);
        leader.setOperate(1);
        leader.setStatus(1);

        clubLeaderMapper.insert(leader);

        // 发送系统通知信息
        User user = userMapper.selectById(leader.getUserId());
        Club club = clubMapper.selectById(leader.getClubId());
        SystemNotice systemNotice = new SystemNotice();
        systemNotice.setUserId(leader.getUserId());
        systemNotice.setTitle("您收到一条来自社团"+club.getName()+"的通知！");
        systemNotice.setInfo(user.getName()+"同学你好！恭喜你成为社团"+club.getName()+"的负责人！让我们一起努力让社团变得更好！");
        systemNotice.setTime(new Date(System.currentTimeMillis()));

        return R.success("成功添加社团负责人！");
    }
}
